package com.kehutong.work.order.manage.service;

import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;
import com.kehutong.common.DoveClient;
import com.kehutong.common.Java8TimeUtils;
import com.kehutong.common.dto.UniformSendReqDto;
import com.kehutong.common.enums.MessageBusinessEnum;
import com.kehutong.common.enums.OperateType;
import com.kehutong.common.enums.TemplateType;
import com.kehutong.common.urlconfig.WebUrlConfig;
import com.kehutong.common.util.TemplateReplaceUtil;
import com.kehutong.common.util.Token;
import com.kehutong.work.order.manage.entity.WorkOrderManage;
import com.kehutong.work.order.manage.entity.WorkOrderManageAppraisal;

@WebService("/work/order/manage/appraisal/service")
public class WorkOrderAppraisalService {

    private static Logger logger = LoggerFactory.getLogger(WorkOrderAppraisalService.class);

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private DoveClient doveClient;
    @Inject
    private WebUrlConfig webUrlConfig;

    public Object listPage(JSONObject jsonObject) {

        return Result.success(jdbcSession.findPage(WorkOrderManageAppraisal.class)
                                         .eq(jsonObject, "userShow", "workOrderId")
                                         .order("userCreate", "desc")
                                         .order("createTime", "desc")
                                         .page(jsonObject)
                                         .exe());
    }

    public Object save(WorkOrderManageAppraisal appraisal, Token token) {
        WorkOrderManage order = Pool.get(WorkOrderManage.class, appraisal.getWorkOrderId());
        if (appraisal.isUserShow() && appraisal.isUserCreate()) { // 用户评论
            WorkOrderManageAppraisal appraisalTemp = jdbcSession.findOne(WorkOrderManageAppraisal.class)
                                                                .eq("workOrderId", appraisal.getWorkOrderId())
                                                                .eq("userNo", appraisal.getUserNo())
                                                                .eq("userShow", true)
                                                                .exe();
            if (Objects.nonNull(appraisalTemp)) {
                return Result.error(0, "您已进行评价！");
            }
            order.setUserAppraisal(true);
            jdbcSession.updateById(order);

                order.getHandleEmployeeNo().forEach(handle -> {
                    try {
                        sendExternalSponsorReply(appraisal, appraisal.getWorkOrderId(), handle, false, TemplateType.WO_B_REPLY, null);
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                });

        } else if(appraisal.isUserShow()){ // 管家回复用户评论
            try {
                if (Objects.nonEmpty(order.getCreatePhone())){
                    sendExternalSponsorReply(appraisal, appraisal.getWorkOrderId(), order.getCreateUserNo(), true, TemplateType.WO_C_REPLY, order.getCreatePhone());

                } else {
                    sendExternalSponsorReply(appraisal, appraisal.getWorkOrderId(), order.getCreateUserNo(), true, TemplateType.WO_C_REPLY, null);
                }

            } catch (Exception e){
                logger.error(e.getMessage(), e);
            }
        } else { // 管家内部评论
            // 内部工单不触发
            // order.getHandleEmployeeNo().forEach(handle -> {
            //     try {
            //         sendExternalSponsorReply(appraisal.getWorkOrderId(), handle, appraisal.isUserCreate(), TemplateType.WO_B_REPLY);
            //     } catch (Exception e) {
            //         logger.error(e.getMessage(), e);
            //     }
            // });
        }

        try {
            if(appraisal.isUserCreate()){
                //新增客户轨迹-评论工单
                doveClient.post("/auth/accountOperateLog/service/add", (http) -> {
                    JSONObject body = new JSONObject();
                    body.put("accountNo",appraisal.getUserNo());
                    body.put("type", OperateType.COMMENT_WORK_ORDER.getId());
                    body.put("desc", "评论工单");
                    body.put("createBy", token.getUuid());
                    body.put("createName", token.getUsername());
                    body.put("companyNo",token.getCompanyNo());
                    body.put("companyName",token.getCompanyName());
                    http.setBody(body.toJSONString());
                });
            }
        } catch (Exception e){
            logger.error(e.getMessage(), e);
        }

        jdbcSession.insert(appraisal);

        return Result.success();
    }

    private void sendExternalSponsorReply(WorkOrderManageAppraisal appraisal, String workOrderId, String uuid, boolean userCreate, TemplateType templateType, String phone) throws Exception {
        WorkOrderManage manage = Pool.get(WorkOrderManage.class, workOrderId);

        // 获取消息推送配置文件
        JSONObject configJson = doveClient.post("/crm/message/global/config/service/get", (http) -> {
            http.addParam("templateType", templateType.getId());
        });
        if (configJson.getIntValue("code") == 200) {
            // 消息推送
            doveClient.post("/crm/message/service/uniformSend", (http) -> {
                UniformSendReqDto dto = new UniformSendReqDto();
                dto.setMsgId(workOrderId);
                dto.setBusinessTypeId(MessageBusinessEnum.MSG_WORK_ORDER.getId());
                dto.setTemplateTypeId(templateType.getId());
                dto.setUserCreate(userCreate);
                dto.setUuid(uuid);
                dto.setCompanyNo(manage.getCompanyNo());
                dto.setTitle(manage.getName());

                JSONObject dataJson = configJson.getJSONObject("data");
                JSONObject inner = dataJson.getJSONObject("messageTemplateInner");
                if (dataJson.getBooleanValue("innerSend") && Objects.nonNull(inner)){
                    dto.setTitle(inner.getString("title"));
                    dto.setInnerData(TemplateReplaceUtil.replace(inner.getString("content"), inner.getString("tagArray"), manage));
                }

                JSONObject app = dataJson.getJSONObject("messageTemplateApp");
                if (dataJson.getBooleanValue("appSend") && Objects.nonNull(app)) {
                    dto.setTitle(app.getString("title"));
                    dto.setAppData(TemplateReplaceUtil.replace(app.getString("content"), app.getString("tagArray"), manage));

                    String param = "?tab=c";

                    dto.setAppToUrl(webUrlConfig.getUrl("/web-app/?page=order/" + manage.getId() + "/2" + URLEncoder.encode(param, "UTF-8")));
                }

                JSONObject sms = dataJson.getJSONObject("messageTemplateSms");
                if (dataJson.getBooleanValue("smsSend") && Objects.nonNull(sms)){
                    if (Objects.nonEmpty(phone)){
                        dto.setPhoneList(Arrays.asList(phone));
                        dto.setSmsDataParams(TemplateReplaceUtil.listTencentSmsParam(sms.getString("content"), sms.getString("tagArray"), manage));
                    } else {
                        JSONObject jsonObject = doveClient.post("/kht-bin/auth/user/listPhone", http1 -> {
                            JSONObject temp = new JSONObject();
                            temp.put("id", Arrays.asList(uuid));
                            http1.setBody(temp.toJSONString());
                        });
                        List<String> listPhone = JSONArray.parseArray(jsonObject.getString("data"), String.class);
                        if (Objects.nonEmpty(listPhone)){
                            dto.setPhoneList(listPhone);
                            dto.setSmsDataParams(TemplateReplaceUtil.listTencentSmsParam(sms.getString("content"), sms.getString("tagArray"), manage));
                        }
                    }
                }

                String wxchatTemplate = dataJson.getString("wxchatTemplate");
                if (dataJson.getBooleanValue("wxchatSend") && Objects.nonNull(wxchatTemplate)) {
                    dto.setWxChatData(getWxchatTemplate(templateType, appraisal));
                    if (TemplateType.WO_C_SUCCESS == templateType){
                        dto.setPageParam(String.format("id=%s&companyNo=%s", manage.getId(), manage.getCompanyNo()));
                    } else if (TemplateType.WO_C_REPLY == templateType){
                        dto.setPageParam(String.format("id=%s&companyNo=%s&tabsActive=1", manage.getId(), manage.getCompanyNo()));
                    } else {

                    }
                }

                http.addParam("temp", JSONObject.toJSONString(dto));

                // http.setBody(JSONObject.toJSONString(dto));
            });
        }
    }

    private String getWxchatTemplate(TemplateType templateType, WorkOrderManageAppraisal appraisal){
        JSONObject data = new JSONObject();

        if(TemplateType.WO_C_REPLY == templateType){
            String appraisalName = appraisal.getUserName();
            String appraisalComment = appraisal.getComment();
            String appraisalTime = Java8TimeUtils.parseString(appraisal.getCreateTime().toLocalDateTime());

            data.put("first", buildMpMessageData("您的工单评价收到新的回复"));
            // 评价人
            data.put("keyword1", buildMpMessageData(appraisalName));
            // 评价内容
            data.put("keyword2", buildMpMessageData(appraisalComment));
            // 评价时间
            data.put("keyword3", buildMpMessageData(appraisalTime));

            data.put("remark", buildMpMessageData("祝您生活愉快！"));
            return data.toJSONString();
        } else {
            return null;
        }
    }

    private JSONObject buildMpMessageData(String value) {
        JSONObject json = new JSONObject();
        json.put("value", value);
        return json;
    }

}
